package qs.openxt.libs.plugins;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import qs.openxt.libs.update.AutoUpdateEx;
import qs.openxt.libs.util.ActivityUtil;
import qs.openxt.libs.util.JSONUtil;
import qs.openxt.libs.util.StringUtil;

/**
 * 获取GPS
 *
 * @author 颖杰_2
 */
public class AutoUpdateExPlugins extends CordovaPlugin {

    private CallbackContext callbackContext;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1: {
                    callbackContext.success((String) msg.obj);
                    break;
                }
                case 2: {
                    Toast.makeText(cordova.getActivity(), (String) msg.obj, Toast.LENGTH_LONG).show();
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

    private void sendMessage(int what, String mMessage){
        Message msg = new Message();
        msg.what = what;
        msg.obj = mMessage;
        mHandler.sendMessage(msg);
    }

    public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException {
        this.callbackContext = callbackContext;
        if ("doCallbackAppVersion".equals(action)) {
            sendMessage(1, ActivityUtil.getVersion(cordova.getActivity()));
            return true;
        }else if ("doAutoUpdateEx".equals(action)) {
            String url = args.optString(0);
            if(!StringUtil.isNull(url)){
                Object data = args.opt(1);
                if(data instanceof JSONObject){
                    data = JSONUtil.toJSON((JSONObject)data);
                }
                String isShowWait = args.optString(2);
                //调用更新
                AutoUpdateEx autoUpdateEx = new AutoUpdateEx(cordova.getActivity(), url, data, "true".equals(isShowWait) ? true : false);
                autoUpdateEx.update();
            }
            return true;
        }else if ("println".equals(action)) {
            new AlertDialog.Builder(cordova.getActivity())
                    .setTitle("温馨提示")
                    .setMessage(args.optString(0))
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).show();
            return true;
        }
        return false;
    }

}
